/**
 * 时间组件
 */
export default class TimerComponent implements Chaos.IDisposable {
    private static instance: TimerComponent = new TimerComponent();
    public static get Default(): TimerComponent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);

        for (const timerId of this.timerIds) {
            window.clearTimeout(timerId);
        }
        this.timerIds.clear();
    }

    private timerIds: Array<number> = [];

    public WaitAsync(millisecond: number): Promise<void> {
        return new Promise(reslove => this.timerIds.add(window.setTimeout(reslove, millisecond)));
    }

    public WaitTillAsync(millisecond: number): Promise<void> {
        return new Promise(reslove => {
            if (Date.now() >= millisecond) {
                reslove();
            } else {
                this.timerIds.add(window.setTimeout(reslove, Date.now() - millisecond));
            }
        });
    }
}